package com.byt.framlib.commonutils;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;


/**
 * 工具类，处理TextView中MaxLines与ellipsize=end冲突问题，实现多行文字最后一行可以在末尾显示...
 */
public class TextViewTool {
    private static TextViewTool tvTool = null;

    private TextViewTool() {

    }

    public static TextViewTool getInstance() {
        if (null == tvTool) {
            tvTool = new TextViewTool();
        }
        return tvTool;
    }

    /**
     * 参数：TextView 要限制行数的TextView，maxLines：控制的行数，content:TextView中要显示的内容
     */
    public void setMaxEcplise(final TextView mTextView, final int maxLines, final String content) {

        ViewTreeObserver observer = mTextView.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                mTextView.setText(content);
                if (mTextView.getLineCount() > maxLines) {
                    int lineEndIndex = mTextView.getLayout().getLineEnd(maxLines - 1);
                    String text = content.subSequence(0, lineEndIndex - 1) + "...";// 网上的资料是linEndIndex-3,发现效果不好，改成1了
                    mTextView.setText(text);
                }
                removeGlobalOnLayoutListener(mTextView.getViewTreeObserver(), this);
            }
        });
    }


    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    private void removeGlobalOnLayoutListener(ViewTreeObserver obs, OnGlobalLayoutListener listener) {
        if (obs == null) return;
        if (Build.VERSION.SDK_INT < 16) {
            obs.removeGlobalOnLayoutListener(listener);
        } else {
            obs.removeOnGlobalLayoutListener(listener);
        }
    }
}